<?php

namespace App\Console\Commands\Lib;


use Carbon\Carbon;

trait ByNow
{
    /**
     * 该属性值初始化后不能变化，如果需要操作时间请使用now()
     * @var Carbon
     */
    protected $now;

    /**
     * 获取当前DT对象
     * @return Carbon
     */
    protected function now()
    {
        if (!$this->now) {
            $this->initNow();
        }
        return clone $this->now;
    }

    /**
     * 初始化当前时间
     */
    protected function initNow()
    {
        $this->now = Carbon::now();
    }

    /**
     * 获取多少分钟前的时间
     * @param $minutes
     * @param bool $timestamp
     * @return int|string
     */
    protected function getDateAgo($minutes, $timestamp = false)
    {
        $date = $this->now()->subMinutes($minutes);
        return $timestamp ? $date->timestamp : $date->toDateString();
    }

    /**
     * 获取多少分钟前的时间区间
     * @param $minutes
     * @param bool $timestamp
     * @return array
     */
    protected function getPeriodAgo($minutes, $timestamp = false)
    {
        $start = $this->now()->subMinutes($minutes);
        $end = $this->now();

        if ($timestamp) {
            $start = $start->timestamp;
            $end = $end->timestamp;
        }
        return [(string)$start, (string)$end];
    }

    /**
     * 获取几天前的时间区间
     * @param $days
     * @param bool $timestamp
     * @return array
     */
    protected function getDayPeriodAgo($days, $timestamp = false)
    {
        $start = $this->now()->startOfDay()->subDays($days);
        $end = $this->now()->subDays($days)->endOfDay();

        if ($timestamp) {
            $start = $start->timestamp;
            $end = $end->timestamp;
        }
        return [(string)$start, (string)$end];
    }

    /**
     * 判断目前是否N分钟的时间点上
     * @param int $minute
     * @return bool
     */
    protected function isPerMinutes($minute)
    {
        $minute = (int)$minute;
        return ($minute + $this->now()->minute) % $minute === 0;
    }
}